package com.example.scene;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.entity.IEntity;
import org.andengine.entity.IEntityFactory;
import org.andengine.entity.modifier.AlphaModifier;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.MoveYModifier;
import org.andengine.entity.modifier.ParallelEntityModifier;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.modifier.ScaleModifier;
import org.andengine.entity.particle.ParticleSystem;
import org.andengine.entity.particle.emitter.PointParticleEmitter;
import org.andengine.entity.particle.initializer.VelocityParticleInitializer;
import org.andengine.entity.particle.modifier.AlphaParticleModifier;
import org.andengine.entity.particle.modifier.ExpireParticleInitializer;
import org.andengine.entity.particle.modifier.RotationParticleModifier;
import org.andengine.entity.particle.modifier.ScaleParticleModifier;
import org.andengine.entity.primitive.Line;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.sprite.TiledSprite;
import org.andengine.entity.text.Text;
import org.andengine.input.touch.TouchEvent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.MotionEvent;
import com.example.base.BaseScene;
import com.example.fruitpool.Point;
import com.example.input.Score;
import com.example.manager.PauseableTimerHandler;
import com.example.manager.ResourcesManager;
import com.example.manager.SceneManager;
import com.example.manager.SceneManager.SceneType;

public class ResultScene extends BaseScene implements IOnSceneTouchListener {

	boolean done;
	//private int[] highScores = new int[5];
	private ArrayList<Score> arr = new ArrayList<Score>();
	
	public ResultScene() {
		
	} 
/*	public void save()
	{

arr = resourcesManager.getScoreFromSharedPreferences();
	
		
		highScores[4] = scores.getInt("WAV-4", 2);
		highScores[3] = scores.getInt("WAV-3", 2);
		highScores[2] = scores.getInt("WAV-2", 2);
		highScores[1] = scores.getInt("WAV-1", 2);
		highScores[0] = scores.getInt("WAV-0", 2);
	 
		boolean newTop = false;
		//ArrayList<Score> arrNew = new ArrayList<Score>();
		//arrNew = arr;
		Score scoreNew = new Score();
		//score = 51;
		for(int i=0;i<arr.size();i++){
			Score s = arr.get(i);
			Log.d("result", s.player+":"+s.score);
		}
		Log.d("result", score+"");
   	 for (int i=4; i>-1; i--){
   		 if (score > arr.get(i).score){
   			 arrNew.set(i, scoreNew);
   			 for (int j=i-1; j>-1; j--){
   				arrNew.set(j, arr.get(j+1));
   			 }
   			 if (i==4) newTop = true;
   			 break;
   		 } else {
   			arrNew.set(i, arr.get(i));
   		 }
   	 }
		Score[] ss = resourcesManager.SortHighScoresByScore(arr, score);
   	for(int i=0;i<5;i++){
		Score s = ss[i];
		Log.d("result", s.player+":"+s.score); 
	}
   	 //for (int i=0; i<5; i++) highScores[i] = newHighScores[i];
	//resourcesManager.saveScores(ss);
	
	arr = resourcesManager.getScoreFromSharedPreferences();
	}*/
	ServerScore server;
	@Override
	public void createScene() {
		setBackgroundEnabled(true);
		server=new ServerScore();
		/*Text result = new Text(0, 0, resourcesManager.font, "Game Over", vbom);
		final int x = (int) (activity.CAMERA_WIDTH / 2 - result.getWidth() / 2);
		final int y = (int) (activity.CAMERA_HEIGHT / 2 - result.getHeight() / 2);
		result.setPosition(x, activity.mCamera.getHeight() + result.getHeight());
		done = false;
		MoveYModifier mod = new MoveYModifier(2, result.getY(), y) {
			@Override
			protected void onModifierFinished(IEntity pItem) {
				done = true;
				createViewScore();
			}
		};
		result.registerEntityModifier(mod);
		attachChild(result); */
		createViewScore();
		this.setOnSceneTouchListener(this);
	}
	RotationModifier updateR;
	TiledSprite update;
	Sprite back,retry;
	private void createViewScore() {
		Sprite spriteBackground=new Sprite(0, 0, activity.CAMERA_WIDTH,
				activity.CAMERA_HEIGHT,
				resourcesManager.game_background_region, vbom);
		ScaleModifier scale=new ScaleModifier(1f, 0, 1);
		AlphaModifier alpha=new AlphaModifier(1f, 0, 1);
		RotationModifier rotate=new RotationModifier(1f, 0, 360){

			@Override
			protected void onModifierFinished(IEntity pItem) {
				// TODO Auto-generated method stub
				super.onModifierFinished(pItem);
				final Sprite spriteScore=new Sprite(50, -50, 200,70,
						resourcesManager.score_region, vbom);
				MoveYModifier score = new MoveYModifier(0.7f, spriteScore.getY(), 50){

					@Override
					protected void onModifierFinished(IEntity pItem) {
						// TODO Auto-generated method stub
						super.onModifierFinished(pItem);
						createScore(spriteScore);
						update=new TiledSprite(activity.CAMERA_WIDTH/2-resourcesManager.retry_region.getWidth()/2-180, 300,160,160, resourcesManager.mTiledTextureRegionUpdate, vbom);
						update.setCurrentTileIndex(0);
						retry=new Sprite(activity.CAMERA_WIDTH/2-resourcesManager.retry_region.getWidth()/2, 290,160,160, resourcesManager.retry_region, vbom);
						back=new Sprite(activity.CAMERA_WIDTH/2-resourcesManager.retry_region.getWidth()/2+180, 300,160,160, resourcesManager.backresault_region, vbom);
						updateR=new RotationModifier(15f, 360, 0);
						update.registerEntityModifier(new LoopEntityModifier(updateR));
						retry.registerEntityModifier(new LoopEntityModifier(new ParallelEntityModifier(new RotationModifier(15f,360, 0))));
						back.registerEntityModifier(new LoopEntityModifier(new ParallelEntityModifier(new RotationModifier(15f, 360, 0))));
						attachChild(update);
						attachChild(retry);
						attachChild(back);
					}
				};	
				spriteScore.registerEntityModifier(score);
				attachChild(spriteScore);
			}
		};
		spriteBackground.registerEntityModifier(new ParallelEntityModifier(scale,rotate,alpha));
		/*MoveXModifier mod= new MoveXModifier(1f, spriteBackground.getX(), -1){
			@Override
			protected void onModifierFinished(IEntity pItem) {
				// TODO Auto-generated method stub
				super.onModifierFinished(pItem);
				final Sprite spriteScore=new Sprite(50, -50, 200,70,
						resourcesManager.score_region, vbom);
				MoveYModifier score = new MoveYModifier(0.7f, spriteScore.getY(), 50){

					@SuppressWarnings("deprecation")
					@Override
					protected void onModifierFinished(IEntity pItem) {
						// TODO Auto-generated method stub
						super.onModifierFinished(pItem);
						createScore(spriteScore);
						
						int score = Integer.parseInt(GameScene.score);
						if(verLocalHighScore(score))//neu diem lon hon local
						{
							//hien dialog cap nhat
						}else{
							
						}
						//activity.showDialog(3);
						if(verServerHighScore(score)){
							SharedPreferences login = activity.getSharedPreferences("login", activity.MODE_PRIVATE);
							SharedPreferences.Editor loginEditor = login.edit();
							boolean onlogin=login.getBoolean("onlogin", false);
							if(onlogin){
								String user=login.getString("user", "unknown");
								activity.message="Name:\n"+user+"Score:\n"+GameScene.score;
								activity.runOnUiThread(new Runnable() {			
									@Override
									public void run() {
										// TODO Auto-generated method stub
										activity.showDialog(5);
									} 
								});	
							}else{
								activity.runOnUiThread(new Runnable() {			
									@Override
									public void run() {
										// TODO Auto-generated method stub
										activity.showDialog(3);
									} 
								});	
							}
						}else{
							
						}
					}
				};
				spriteScore.registerEntityModifier(score);
				attachChild(spriteScore);
			}	
		};*/
		//spriteBackground.registerEntityModifier(sc);
		attachChild(spriteBackground);
		saveScore();
	}
	int x1Convert, y1Convert, x2Convert, y2Convert;
	public void convertTouch(int x1, int y1, int x2, int y2)
	{
		x1Convert = (int) (x1*resourcesManager.wRate);
		y1Convert = (int) (y1*resourcesManager.hRate);
		x2Convert = (int) (x2*resourcesManager.wRate);
		y2Convert = (int) (y2*resourcesManager.hRate);
		
		Log.d("inconvert", x1+"->"+x1Convert+":"+y1+"->"+y1Convert);
	}
	
	public void waiting()
	{
		updateR.reset(1f, 0, 360);
		update.setCurrentTileIndex(1);
	}
	public void unwaiting()
	{
		updateR.reset(3f, 0, 360);
		update.setCurrentTileIndex(0);
	}

	Point currPoint=new Point(); 
	Point prevPoint=new Point();
	Line line;
	PauseableTimerHandler p;
	boolean touch=true;
	public boolean slash=true;
	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		// TODO Auto-generated method stub
		synchronized (this) {
			switch (pSceneTouchEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:
				currPoint=new Point();
				currPoint.x=(int) pSceneTouchEvent.getMotionEvent().getX();
				currPoint.y=(int) pSceneTouchEvent.getMotionEvent().getY();
				break;
			case MotionEvent.ACTION_UP:
				this.detachChild(line);
				slash=true;
				touch=true;
				break; 
			case MotionEvent.ACTION_MOVE:
				prevPoint=new Point();
				prevPoint.x = (int) pSceneTouchEvent.getMotionEvent().getX();
				prevPoint.y = (int) pSceneTouchEvent.getMotionEvent().getY();
				Log.d("prevPoint",prevPoint.x+":"+prevPoint.y);
				convertTouch(prevPoint.x, prevPoint.y,currPoint.x, currPoint.y);
				line = new Line(x2Convert,y2Convert,x1Convert,y1Convert,vbom);
				Log.d("x2Convert",x2Convert+":"+y2Convert+"-"+x1Convert+":"+y1Convert);
				line.setLineWidth(3);
				line.setAlpha(0);
				//this.attachChild(line);
				//Log.d("update",update.getWidth()+":"+update.getHeight());
				if(update!=null && update.collidesWith(line))
				{
					//Log.d("checkScore",server.checkScore()+"");
					if(server.touch1){
						resourcesManager.sliceSound.play();
						server.checkScore();
						 p=new PauseableTimerHandler(0.5f, true, new ITimerCallback() {
							
							@Override
							public void onTimePassed(TimerHandler pTimerHandler) {
								// TODO Auto-generated method stub
								Log.d("checkscore",server.checkscore+"");
								 if(server.checkscore==1||server.checkscore==2){
									
									 if(server.checkscore==1){
										 	SharedPreferences login = activity.getSharedPreferences("login", activity.MODE_PRIVATE);
											SharedPreferences.Editor loginEditor = login.edit();
											boolean onlogin=login.getBoolean("onlogin", false);
											if(onlogin){
												final String user=login.getString("user", "unknown");		
												activity.runOnUiThread(new Runnable() {			
													@Override
													public void run() {
		
															activity.message=null;
															activity.message="Name: "+user+"\nScore: "+GameScene.score;
															activity.showDialog(6);
														
													} 
												});	
											}else{
												activity.runOnUiThread(new Runnable() {			
													@Override
													public void run() {
														// TODO Auto-generated method stub
															activity.showDialog(3);
														
													} 
												});	
											}
										}else{
											activity.runOnUiThread(new Runnable() {			
												@Override
												public void run() {
													// TODO Auto-generated method stub
														activity.message=null;
														activity.message="Điểm của bạn chưa vào top 10 trên server!";
														activity.showDialog(4);
													
												} 
											});	
										}
									 p.mPause=true;
									 p.setAutoReset(false);
									 resourcesManager.engine.unregisterUpdateHandler(p);
								 }
							}
						});
						 resourcesManager.engine.registerUpdateHandler(p);
					}
				}
				
				if(retry!=null &&retry.collidesWith(line))
				{
					Log.d("retry","retry");
					resourcesManager.sliceSound.play();
					GameScene.score=null;
					if(touch){
						touch=false;
						SceneManager.getInstance().loadGameScene(engine);
					}
				}
				
				if(back!=null &&back.collidesWith(line))
				{
					resourcesManager.sliceSound.play();
					GameScene.score=null;
					if(touch){
						touch=false;
						SceneManager.getInstance().loadMenuScene(engine);
					}
				}
				currPoint = prevPoint;
				break;
			}
			return true;
		}
	}
	
	Text text;
	private void createScore(Sprite spriteScore) {
		text = new Text(0, 0, resourcesManager.font, "0", 100, vbom);
		text.setColor(org.andengine.util.color.Color.YELLOW);
		text.setPosition(100, spriteScore.getY()+spriteScore.getHeight()+10);
		text.setText(GameScene.score);
		this.attachChild(text);
		createExplosion(text.getX()+text.getWidth()/2,text.getY()+text.getHeight()/2,text.getParent());
		
	}
	
	public boolean verLocalHighScore(int score)
	{
		
		return false;
	}
	@Override
	public void onBackKeyPressed() {
		// TODO Auto-generated method stub
		GameScene.score=null;
		SceneManager.getInstance().loadMenuScene(engine);
	}

	@Override
	public SceneType getSceneType() {
		// TODO Auto-generated method stub
		return SceneType.SCENE_RESULT;
	}

	@Override
	public void disposeScene() {
		// TODO Auto-generated method stub
		
	}
	private void createExplosion(final float posX, final float posY,final IEntity target) {
		int mNumPart = 30;
		int mTimePart = 2;
		PointParticleEmitter particleEmitter = new PointParticleEmitter(posX,posY);
		IEntityFactory<Sprite> recFact = new IEntityFactory<Sprite>() {
			@Override
			public Sprite create(float pX, float pY) {
				Sprite rect = new Sprite(pX, pY, resourcesManager.star_region, vbom);
				return rect;
			}

		};
		final ParticleSystem<Sprite> particleSystem = new ParticleSystem<Sprite>(recFact, particleEmitter, 500, 500, mNumPart);
		particleSystem.addParticleInitializer(new VelocityParticleInitializer<Sprite>(-100, 100, -100, 100));
		//particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(0,0.6f * mTimePart, 1, 0));
		particleSystem.addParticleModifier(new RotationParticleModifier<Sprite>(0,mTimePart, 0, 360));
		particleSystem.addParticleInitializer(new ExpireParticleInitializer<Sprite>(3.5f));
		
		particleSystem.addParticleModifier(new ScaleParticleModifier<Sprite>(0, 3, 0.5f, 1.0f));
		particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(2.5f, 3.5f, 1.0f, 0.0f));
		particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(3.5f, 4.5f, 0.0f, 1.0f));
		particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(4.5f, 11.5f, 1.0f, 0.0f));
		
		target.attachChild(particleSystem);
	}
	public void saveScore()
	{
		String t = GameScene.score;
		int tt = Integer.parseInt(t);
		Score s = new Score("supper", tt);
		arr = resourcesManager.getScoreFromSharedPreferences();		
		Score[] ss = resourcesManager.SortHighScoresByScore(arr, s);		
		// for (int i=0; i<5; i++) highScores[i] = newHighScores[i];
		resourcesManager.saveScores(ss);
		arr = resourcesManager.getScoreFromSharedPreferences();
		for(int i=0;i<arr.size();i++){
			Log.d("arr", arr.get(i).player+":"+arr.get(i).score);
		}
	}
}
